#include "orderdetailwidget.h"
#include "usermanager.h"
#include "errorhandler.h"
#include <QHeaderView>
#include <QDateTime>

OrderDetailWidget::OrderDetailWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_scrollArea(nullptr)
    , m_contentWidget(nullptr)
    , m_contentLayout(nullptr)
    , m_basicInfoGroup(nullptr)
    , m_basicInfoLayout(nullptr)
    , m_orderIdLabel(nullptr)
    , m_statusLabel(nullptr)
    , m_createTimeLabel(nullptr)
    , m_completeTimeLabel(nullptr)
    , m_totalAmountLabel(nullptr)
    , m_paymentMethodLabel(nullptr)
    , m_customerInfoGroup(nullptr)
    , m_customerInfoLayout(nullptr)
    , m_customerNameLabel(nullptr)
    , m_customerIdLabel(nullptr)
    , m_itemsGroup(nullptr)
    , m_itemsLayout(nullptr)
    , m_itemsTable(nullptr)
    , m_itemsSummaryLabel(nullptr)
    , m_emptyStateLabel(nullptr)
    , m_hasOrder(false)
{
    setupLayout();
}

OrderDetailWidget::~OrderDetailWidget()
{
    // Qt会自动清理子对象
}

void OrderDetailWidget::setOrder(const Order& order)
{
    if (!order.isValid()) {
        clearOrder();
        return;
    }
    
    m_currentOrder = order;
    m_hasOrder = true;
    
    // 隐藏空状态，显示内容
    m_emptyStateLabel->hide();
    m_contentWidget->show();
    
    try {
        populateOrderInfo(order);
        populateOrderItems(order.items);
        populateCustomerInfo(order.customerId);
        
        LOG_INFO(QString("订单详情已显示: %1").arg(order.id), "OrderDetailWidget");
        
    } catch (const std::exception& e) {
        HANDLE_ERROR(ErrorLevel::ERROR, "显示订单详情失败", 
                     QString::fromStdString(e.what()), false);
        clearOrder();
    }
}

void OrderDetailWidget::clearOrder()
{
    m_currentOrder = Order();
    m_hasOrder = false;
    
    // 显示空状态，隐藏内容
    m_contentWidget->hide();
    m_emptyStateLabel->show();
    
    clearAllContent();
}

bool OrderDetailWidget::hasOrder() const
{
    return m_hasOrder;
}

void OrderDetailWidget::setupLayout()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);
    
    // 创建滚动区域
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    
    // 创建内容容器
    m_contentWidget = new QWidget();
    m_contentLayout = new QVBoxLayout(m_contentWidget);
    m_contentLayout->setContentsMargins(8, 8, 8, 8);
    m_contentLayout->setSpacing(8);
    
    // 创建基本信息组
    m_basicInfoGroup = new QGroupBox("订单基本信息", m_contentWidget);
    m_basicInfoLayout = new QVBoxLayout(m_basicInfoGroup);
    m_basicInfoLayout->setContentsMargins(8, 16, 8, 8);
    m_basicInfoLayout->setSpacing(6);
    
    m_orderIdLabel = new QLabel();
    m_statusLabel = new QLabel();
    m_createTimeLabel = new QLabel();
    m_completeTimeLabel = new QLabel();
    m_totalAmountLabel = new QLabel();
    m_paymentMethodLabel = new QLabel();
    
    m_basicInfoLayout->addWidget(m_orderIdLabel);
    m_basicInfoLayout->addWidget(m_statusLabel);
    m_basicInfoLayout->addWidget(m_createTimeLabel);
    m_basicInfoLayout->addWidget(m_completeTimeLabel);
    m_basicInfoLayout->addWidget(m_totalAmountLabel);
    m_basicInfoLayout->addWidget(m_paymentMethodLabel);
    
    // 创建顾客信息组
    m_customerInfoGroup = new QGroupBox("顾客信息", m_contentWidget);
    m_customerInfoLayout = new QVBoxLayout(m_customerInfoGroup);
    m_customerInfoLayout->setContentsMargins(8, 16, 8, 8);
    m_customerInfoLayout->setSpacing(6);
    
    m_customerNameLabel = new QLabel();
    m_customerIdLabel = new QLabel();
    
    m_customerInfoLayout->addWidget(m_customerNameLabel);
    m_customerInfoLayout->addWidget(m_customerIdLabel);
    
    // 创建订单项组
    m_itemsGroup = new QGroupBox("订单项明细", m_contentWidget);
    m_itemsLayout = new QVBoxLayout(m_itemsGroup);
    m_itemsLayout->setContentsMargins(8, 16, 8, 8);
    m_itemsLayout->setSpacing(6);
    
    // 创建订单项表格
    m_itemsTable = new QTableWidget();
    m_itemsTable->setColumnCount(4);
    QStringList headers;
    headers << "菜品名称" << "数量" << "单价" << "小计";
    m_itemsTable->setHorizontalHeaderLabels(headers);
    
    // 设置表格属性
    m_itemsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_itemsTable->setSelectionMode(QAbstractItemView::NoSelection);
    m_itemsTable->setAlternatingRowColors(true);
    m_itemsTable->setSortingEnabled(false);
    m_itemsTable->setShowGrid(true);
    m_itemsTable->verticalHeader()->setVisible(false);
    
    // 设置表格滚动和尺寸策略
    m_itemsTable->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_itemsTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_itemsTable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    
    // 设置行高
    m_itemsTable->verticalHeader()->setDefaultSectionSize(35);
    
    // 设置列宽策略
    QHeaderView* header = m_itemsTable->horizontalHeader();
    header->setStretchLastSection(false);
    
    // 设置列宽比例
    header->setSectionResizeMode(0, QHeaderView::Stretch);    // 菜品名称 - 自适应
    header->setSectionResizeMode(1, QHeaderView::Fixed);      // 数量 - 固定
    header->setSectionResizeMode(2, QHeaderView::Fixed);      // 单价 - 固定
    header->setSectionResizeMode(3, QHeaderView::Fixed);      // 小计 - 固定
    
    // 设置固定列的最小宽度
    header->resizeSection(0, 200);  // 菜品名称最小宽度
    header->resizeSection(1, 80);   // 数量
    header->resizeSection(2, 100);  // 单价
    header->resizeSection(3, 100);  // 小计
    
    // 设置行高
    m_itemsTable->verticalHeader()->setDefaultSectionSize(35);
    
    // 设置表格样式
    m_itemsTable->setStyleSheet(R"(
        QTableWidget {
            border: 1px solid #E0E0E0;
            background-color: white;
            gridline-color: #F0F0F0;
            font-size: 13px;
        }
        QTableWidget::item {
            padding: 8px;
            border-bottom: 1px solid #F0F0F0;
        }
        QTableWidget::item:selected {
            background-color: #E3F2FD;
        }
        QHeaderView::section {
            background-color: #F5F5F5;
            padding: 8px;
            border: none;
            border-bottom: 1px solid #E0E0E0;
            border-right: 1px solid #E0E0E0;
            font-weight: bold;
            font-size: 13px;
        }
    )");
    
    m_itemsSummaryLabel = new QLabel();
    m_itemsSummaryLabel->setAlignment(Qt::AlignRight);
    m_itemsSummaryLabel->setStyleSheet(R"(
        QLabel {
            padding: 8px;
            font-size: 14px;
            background-color: #F8F9FA;
            border: 1px solid #E0E0E0;
            border-radius: 4px;
        }
    )");
    
    m_itemsLayout->addWidget(m_itemsTable);
    m_itemsLayout->addWidget(m_itemsSummaryLabel);
    
    // 添加到内容布局
    m_contentLayout->addWidget(m_basicInfoGroup);
    m_contentLayout->addWidget(m_customerInfoGroup);
    m_contentLayout->addWidget(m_itemsGroup);
    m_contentLayout->addStretch();
    
    // 设置滚动区域内容
    m_scrollArea->setWidget(m_contentWidget);
    
    // 创建空状态标签
    m_emptyStateLabel = new QLabel("请选择一个订单查看详情", this);
    m_emptyStateLabel->setAlignment(Qt::AlignCenter);
    m_emptyStateLabel->setStyleSheet(R"(
        QLabel {
            color: #9E9E9E;
            font-size: 14px;
            padding: 40px;
        }
    )");
    
    // 添加到主布局
    m_mainLayout->addWidget(m_scrollArea);
    m_mainLayout->addWidget(m_emptyStateLabel);
    
    // 初始状态显示空状态
    m_contentWidget->hide();
    m_emptyStateLabel->show();
    
    // 设置样式
    setStyleSheet(R"(
        QGroupBox {
            font-weight: bold;
            font-size: 11px;
            border: 1px solid #D0D0D0;
            border-radius: 4px;
            margin-top: 8px;
            padding-top: 4px;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 8px;
            padding: 0 4px 0 4px;
            background-color: white;
        }
        
        QLabel {
            font-size: 11px;
            padding: 2px;
        }
        
        QTableWidget {
            background-color: white;
            border: 1px solid #D0D0D0;
            font-size: 10px;
            gridline-color: #E0E0E0;
        }
        
        QTableWidget::item {
            padding: 2px 4px;
            border-bottom: 1px solid #E0E0E0;
        }
        
        QHeaderView::section {
            background-color: #F5F5F5;
            border: 1px solid #D0D0D0;
            font-weight: bold;
            padding: 4px;
            font-size: 10px;
        }
        
        QScrollArea {
            border: none;
            background-color: #FAFAFA;
        }
    )");
}

void OrderDetailWidget::populateOrderInfo(const Order& order)
{
    // 订单ID
    m_orderIdLabel->setText(QString("订单号: <b>%1</b>").arg(order.id));
    
    // 状态
    QString statusText = getStatusDisplayText(order.status);
    QString statusColor = getStatusColor(order.status);
    m_statusLabel->setText(QString("状态: <span style='color: %1; font-weight: bold;'>%2</span>")
                          .arg(statusColor, statusText));
    
    // 创建时间
    QString createTimeText = formatDateTime(order.createdDate);
    m_createTimeLabel->setText(QString("创建时间: %1").arg(createTimeText));
    
    // 完成时间
    if (order.completedDate.isValid()) {
        QString completeTimeText = formatDateTime(order.completedDate);
        m_completeTimeLabel->setText(QString("完成时间: %1").arg(completeTimeText));
        m_completeTimeLabel->show();
    } else {
        m_completeTimeLabel->hide();
    }
    
    // 总金额
    QString amountText = formatAmount(order.totalAmount);
    m_totalAmountLabel->setText(QString("总金额: <b style='color: #FF5722; font-size: 12px;'>%1</b>")
                               .arg(amountText));
    
    // 支付方式
    QString paymentText = order.paymentMethod.isEmpty() ? "未指定" : order.paymentMethod;
    m_paymentMethodLabel->setText(QString("支付方式: %1").arg(paymentText));
}

void OrderDetailWidget::populateOrderItems(const QList<OrderItem>& items)
{
    // 清空现有数据
    m_itemsTable->setRowCount(0);
    
    double totalAmount = 0.0;
    int totalItems = 0;
    
    // 添加订单项
    for (int i = 0; i < items.size(); ++i) {
        const OrderItem& item = items[i];
        
        m_itemsTable->insertRow(i);
        
        // 菜品名称
        QTableWidgetItem* nameItem = new QTableWidgetItem(item.menuItemName);
        nameItem->setFlags(nameItem->flags() & ~Qt::ItemIsEditable);
        nameItem->setToolTip(item.menuItemName); // 添加工具提示显示完整名称
        nameItem->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        m_itemsTable->setItem(i, 0, nameItem);
        
        // 数量
        QTableWidgetItem* quantityItem = new QTableWidgetItem(QString::number(item.quantity));
        quantityItem->setFlags(quantityItem->flags() & ~Qt::ItemIsEditable);
        quantityItem->setTextAlignment(Qt::AlignCenter);
        m_itemsTable->setItem(i, 1, quantityItem);
        
        // 单价
        QTableWidgetItem* priceItem = new QTableWidgetItem(formatAmount(item.price));
        priceItem->setFlags(priceItem->flags() & ~Qt::ItemIsEditable);
        priceItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        m_itemsTable->setItem(i, 2, priceItem);
        
        // 小计
        QTableWidgetItem* subtotalItem = new QTableWidgetItem(formatAmount(item.subtotal));
        subtotalItem->setFlags(subtotalItem->flags() & ~Qt::ItemIsEditable);
        subtotalItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        subtotalItem->setFont(QFont("Microsoft YaHei", 10, QFont::Bold));
        m_itemsTable->setItem(i, 3, subtotalItem);
        
        totalAmount += item.subtotal;
        totalItems += item.quantity;
    }
    
    // 动态调整表格高度
    int headerHeight = m_itemsTable->horizontalHeader()->height();
    int rowHeight = m_itemsTable->verticalHeader()->defaultSectionSize();
    int scrollBarHeight = 20; // 滚动条预留高度
    
    // 计算表格内容的理想高度
    int contentHeight = headerHeight + items.size() * rowHeight + scrollBarHeight;
    
    // 设置表格高度：最少显示3行，最多显示8行，避免界面过于拥挤
    int minHeight = headerHeight + 3 * rowHeight + scrollBarHeight;
    int maxHeight = headerHeight + 8 * rowHeight + scrollBarHeight;
    
    int tableHeight = qMax(minHeight, qMin(contentHeight, maxHeight));
    m_itemsTable->setMinimumHeight(minHeight);
    m_itemsTable->setMaximumHeight(tableHeight);
    
    // 更新汇总信息
    m_itemsSummaryLabel->setText(QString("共 <b>%1</b> 项菜品，<b>%2</b> 份，总计: <b style='color: #FF5722;'>%3</b>")
                                .arg(items.size())
                                .arg(totalItems)
                                .arg(formatAmount(totalAmount)));
}

void OrderDetailWidget::populateCustomerInfo(const QString& customerId)
{
    try {
        // 通过DataManager获取顾客信息
        Customer customer = DataManager::instance().getCustomerById(customerId);
        if (customer.isValid() && !customer.username.isEmpty()) {
            m_customerNameLabel->setText(QString("顾客姓名: <span style='color: #2c3e50; font-weight: bold;'>%1</span>").arg(customer.username));
        } else {
            m_customerNameLabel->setText("顾客姓名: <span style='color: #e74c3c;'>未知顾客</span>");
        }
    } catch (const std::exception& e) {
        LOG_WARNING(QString("Failed to get customer info for ID %1: %2").arg(customerId).arg(e.what()), 
                   "OrderDetailWidget::populateCustomerInfo");
        m_customerNameLabel->setText("顾客姓名: <span style='color: #e74c3c;'>查询失败</span>");
    }
    
    m_customerIdLabel->setText(QString("顾客ID: %1").arg(customerId));
}

void OrderDetailWidget::clearAllContent()
{
    // 清空基本信息
    m_orderIdLabel->clear();
    m_statusLabel->clear();
    m_createTimeLabel->clear();
    m_completeTimeLabel->clear();
    m_totalAmountLabel->clear();
    m_paymentMethodLabel->clear();
    
    // 清空顾客信息
    m_customerNameLabel->clear();
    m_customerIdLabel->clear();
    
    // 清空订单项表格
    m_itemsTable->setRowCount(0);
    m_itemsSummaryLabel->clear();
}

QString OrderDetailWidget::getStatusDisplayText(OrderStatus status) const
{
    switch (status) {
        case OrderStatus::PENDING: return "待处理";
        case OrderStatus::PREPARING: return "制作中";
        case OrderStatus::COMPLETED: return "已完成";
        case OrderStatus::CANCELLED: return "已取消";
        default: return "未知";
    }
}

QString OrderDetailWidget::getStatusColor(OrderStatus status) const
{
    switch (status) {
        case OrderStatus::PENDING: return "#FF9800";    // 橙色
        case OrderStatus::PREPARING: return "#2196F3";  // 蓝色
        case OrderStatus::COMPLETED: return "#4CAF50";  // 绿色
        case OrderStatus::CANCELLED: return "#F44336";  // 红色
        default: return "#666666";                       // 灰色
    }
}

QString OrderDetailWidget::formatAmount(double amount) const
{
    return QString("¥%1").arg(amount, 0, 'f', 2);
}

QString OrderDetailWidget::formatDateTime(const QDateTime& dateTime) const
{
    if (!dateTime.isValid()) {
        return "-";
    }
    
    return dateTime.toString("yyyy-MM-dd hh:mm:ss");
}
